package com.ty.controller;

import cn.hutool.core.date.DateUtil;
import com.ty.dao.OrderItemDao;
import com.ty.dao.OrderMasterDao;
import com.ty.dto.OrderingDTO;
import com.ty.dto.OrderingOk;
import com.ty.dto.OrderingProduct;
import com.ty.feignclients.StockClient;
import com.ty.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @PostMapping
    public OrderingOk ordering(@RequestParam OrderingDTO dto) {
        return orderService.ordering(dto);
    }
    /*@Autowired
    private OrderMasterDao masterDao;
    @Autowired
    private OrderItemDao itemDao;
    @Autowired
    StockClient stockClient;

    @PostMapping
    public OrderingOk ordering(@RequestParam OrderingDTO dto) {

        //1.扣减库存
        stockClient.deduct(dto.getProducts().get(0).getProductId(), dto.getProducts().get(0).getQty());
        //2.组装数据

        String yyyyMMddHHmmssSSS = DateUtil.format(DateUtil.date(), "yyyyMMddHHmmss");
        long orderId =  Long.valueOf(yyyyMMddHHmmssSSS);
        dto.setId(orderId);

        Integer insert = masterDao.insert(dto);
        List<OrderingProduct> products = dto.getProducts();

        OrderingProduct orderingProduct = products.get(0);
        orderingProduct.setOrderId(orderId);

        //3.落库
        OrderController proxy = (OrderController) (AopContext.currentProxy());
        proxy.insert(dto);
        return new OrderingOk().setId(orderId).setNeedPay(BigDecimal.TEN);
    }

    @GlobalTransactional(name = "coldCreteOrder")
    //@Transactional
    public void insert(OrderingDTO dto) {
        masterDao.insert(dto);
        itemDao.insert(dto.getProducts().get(0));
    }*/
}
